Title: How to Limit Purchases by Role

Publish Date: Sun, 01 Oct 2017 07:00:00 +0000

Categories: Uncategorized

Content:

Did you ever need to limit purchases for a specific product or category to some customers only?

You can do it with WooCommerce by adding a snippet to your site. Let’s see an example!



Use Case

Let’s say that I have two type of customers, regular customers, and resellers. All products are available to regular customers, but products from the category Music are not available for resellers.

How do I limit them from purchasing those products?

First of all, I need to create the role Reseller and add a generic capability to it, in our case resell_product. I did this by using the plugin [ablank href="https://wordpress.org/plugins/user-role-editor/"]User Role Editor[/ablank], you can check its documentation to learn how to do it.

Once I created the role, I need to write some custom code to prevent them from purchasing from the category Music. So I open my functions.php file in wp-content/themes/my-child-theme-name/ and add this code at the end of it:

https://gist.github.com/SiR-DanieL/eb54200a81b1821b0bf64f42d07aee7a

On line 11 there are two checks:

current_user_can( 'resell_product' ) && in_array( 17, $categories )


The first one checks if the current logged in users is a reseller, based on a custom capability that I added to the role Reseller. The second one checks if the product is in the category with ID 17, which is the ID of the category Music, the one that I want to block the purchases for.

With this code in the file I can’t even see the Add to Cart button on the product page:

[caption id="attachment_3266" align="alignnone" width="2194"] The Add to Cart button is missing from the product page.[/caption]

While on the Shop page I see a Read More button:



And if I click on it, I will be redirected to the Shop page without being able to buy the product.
